/**
 * 
 */
package config;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

/**
 * @author puneet
 * 
 */
public class HaltDetermine {

	public static boolean halt(Path[] outputFilePaths, Path lastMapInput,
			String destination, FileSystem fs) throws IOException {
		
		Map<String, Integer> oldDistancesMap = makeOldDistancesMap(lastMapInput, fs);
		//System.out.println("Old Distances Map:" + oldDistancesMap);
		if(!oldDistancesMap.containsKey(destination)) {
			System.out.println("Havent found destination as yet. Doesnt exist in old map still");
			return false;
		}
		Map<String, Integer> newDistancesMap = makeNewDistancesMap(outputFilePaths, fs);
		//System.out.println("New Distances Map:" + newDistancesMap);
		return newDistancesMap.containsKey(destination) && oldDistancesMap.equals(newDistancesMap); 
	}

	public static Map<String, Integer> makeOldDistancesMap(Path mapInputFile,
			FileSystem fs) throws IOException {
		Map<String, Integer> returnMap = new HashMap<String, Integer>();
		BufferedReader br = new BufferedReader(new InputStreamReader(fs
				.open(mapInputFile)));
		String s = null;
		while ((s = br.readLine()) != null) {
			String[] vals = s.split("\\s");
			returnMap.put(vals[0], Integer.valueOf(vals[1]));
		}
		return returnMap;
	}

	public static Map<String, Integer> makeNewDistancesMap(Path[] outputFiles,
			FileSystem fs)throws IOException {
		Map<String, Integer> returnMap = new HashMap<String, Integer>();
		for (Path p : outputFiles) {
			BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(p)));
			String s = null;
			while ((s = br.readLine()) != null) {
				String[] vals = s.split("\\s");
				returnMap.put(vals[0], Integer.valueOf(vals[1]));
			}
		}
		return returnMap;
	}
}
